package opengraph.api

import opengraph.impl.HtmlFetcherImpl
import opengraph.impl.HtmlParserImpl

class OpenGraph private constructor(private val htmlFetcher: HtmlFetcher, private val htmlParser: HtmlParser) {

    class Builder {
        var htmlFetcher: HtmlFetcher? = null
        var htmlParser: HtmlParser? = null
        fun setHtmlFetcher(htmlFetcher: HtmlFetcher) = apply {
            this.htmlFetcher = htmlFetcher
        }

        fun setHtmlParser(htmlParser: HtmlParser) = apply {
            this.htmlParser = htmlParser
        }

        fun build(): OpenGraph {
            return OpenGraph(htmlFetcher ?: HtmlFetcherImpl(), htmlParser ?: HtmlParserImpl())
        }
    }

    companion object {
        fun builder(): Builder {
            return Builder()
        }
    }

    fun get(url: String): OpenGraphMeta {
        val meta = OpenGraphMeta()
        val html = htmlFetcher.fetch(url)
        if (html.isEmpty()) {
            return meta
        }
        val htmlMeta = htmlParser.parse(html)

        htmlMeta.htmlMetas.forEach {
            val names = it.property.split(":").map(String::trim).toMutableList()
            if(it.type == HtmlMeta.TYPE_OG){
                //处理命名空间
                if(names.size >= 2){
                    if(htmlMeta.namespaceContext.getSchema(names[0]) == NamespaceContext.og){
                        names[0] = OpenGraphMeta.OG_TAG_VAR
                    }
                    //补丁 没有命名空间的情况下 默认og是命名空间
                    else if(names[0] == "og"){
                        names[0] = OpenGraphMeta.OG_TAG_VAR
                    }
                }
            }
            var metaIndex = meta
            for ((i, name) in names.withIndex()) {
                metaIndex = metaIndex.getOrCreate(name)
                if (i == names.size - 1) {
                    metaIndex.content.add(it.value.trim())
                }
            }
        }
        return meta
    }

}
